﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using System.Data.Common;
using Mocola.BLL;
using Mocola.Model;
using Mocola.Net.Web.Utility;
using System.Collections.Generic;
using Mocola.Security;
using Mocola.Web;
using Mocola.Common;

namespace Mocola.Net.Web
{
    public partial class mgfiles : System.Web.UI.Page
    {
        public int RoleId = -1;

        protected void Page_Load(object sender, EventArgs e)
        {
            string IsPassword = ConfigurationManager.AppSettings["PasswordConfirm"];
            lbPwd.Visible = txtPassword.Visible = IsPassword == "1" ? true : false;

            if (!IsPostBack)
            {
                RoleId = MocolaUser.CurrentUser.RoleID; // 得到当前用户所属角色ID号

                BindData();
                /*Begin:[#23]*/
                InitMoc_Tree();
                /*End:[#23]*/
            }
        }

        /* BEGIN: [#5] */
        private void BindData()
        {
            int Eid = Convert.ToInt32(Request.QueryString["eid"]);
            int Tid = Convert.ToInt32(Request.QueryString["tid"]);

            using (DataSet dt = Databases.MocolaNet.Select(Moc_MMapsInfo.Moc_MMaps,
                    Moc_MMapsInfo.Moc_MMaps.ID,
                    Moc_MMapsInfo.Moc_MMaps.Name,
                    Moc_MMapsInfo.Moc_MMaps.JueDingHao,
                    Moc_MMapsInfo.Moc_MMaps.TuZhiBianHao,
                    Moc_MMapsInfo.Moc_MMaps.ZhuanYeLeiBie,
                    Moc_MMapsInfo.Moc_MMaps.ChuTuRiQi,
                    Moc_MMapsInfo.Moc_MMaps.SheJiDanWei,
                    Moc_MMapsInfo.Moc_MMaps.BanBen,
                    Moc_MMapsInfo.Moc_MMaps.TuFu,
                    Moc_MMapsInfo.Moc_MMaps.Zhang,
                    Moc_MMapsInfo.Moc_MMaps.Tao,
                    Moc_MMapsInfo.Moc_MMaps.ShuLiang,
                    Moc_MMapsInfo.Moc_MMaps.ZaiTi,
                    Moc_MMapsInfo.Moc_MMaps.CaiZhi,
                    Moc_MMapsInfo.Moc_MMaps.MiJi,
                    Moc_MMapsInfo.Moc_MMaps.BaoGuanQiXian,
                    Moc_MMapsInfo.Moc_MMaps.ZhuangTai,
                    Moc_MMapsInfo.Moc_MMaps.FaQiBuMen,
                    Moc_MMapsInfo.Moc_MMaps.YiJiaoRen,
                    Moc_MMapsInfo.Moc_MMaps.JiShouRen,
                    Moc_MMapsInfo.Moc_MMaps.JiShouRiQi,
                    Moc_MMapsInfo.Moc_MMaps.BeiZhu)
                    .Where((Moc_MMapsInfo.Moc_MMaps.Tid == Tid) && (Moc_MMapsInfo.Moc_MMaps.Eid == Eid))
                    .ToDataSet())
            {
                PagedDataSource pg = new PagedDataSource();
                ppMaps.RecordCount = dt.Tables[0].Rows.Count;

                DataView dv = dt.Tables[0].DefaultView;
                dv.Sort = SortString;
                pg.DataSource = dv;
                pg.AllowPaging = true;
                pg.PageSize = ppMaps.PageSize;
                pg.CurrentPageIndex = ppMaps.CurrentPageIndex - 1;
                rptMaps.DataSource = pg;
                rptMaps.DataBind();

                ppMaps.CustomInfoHTML = string.Format("第<font color='red'>{0}</font>/{1}", ppMaps.CurrentPageIndex.ToString(), ppMaps.PageCount.ToString() + "页  每页" + ppMaps.PageSize.ToString() + "条" + " 共" + ppMaps.RecordCount.ToString() + "条记录");
                ppMaps.CustomInfoStyle = "padding-right:10px;text-align:center;";
            }

            using (DataSet dt2 = Databases.MocolaNet.Select(Moc_MFilesInfo.Moc_MFiles,
                    Moc_MFilesInfo.Moc_MFiles.ID,
                    Moc_MFilesInfo.Moc_MFiles.Name,
                    Moc_MFilesInfo.Moc_MFiles.JueDingHao,
                    Moc_MFilesInfo.Moc_MFiles.WenJianHao,
                    Moc_MFilesInfo.Moc_MFiles.ShenQingHao,
                    Moc_MFilesInfo.Moc_MFiles.FaWenDanWei,
                    Moc_MFilesInfo.Moc_MFiles.FaWenRiQi,
                    Moc_MFilesInfo.Moc_MFiles.ShuLiang,
                    Moc_MFilesInfo.Moc_MFiles.ZaiTi,
                    Moc_MFilesInfo.Moc_MFiles.CaiZhi,
                    Moc_MFilesInfo.Moc_MFiles.MiJi,
                    Moc_MFilesInfo.Moc_MFiles.BaoGuanQiXian,
                    Moc_MFilesInfo.Moc_MFiles.ZhuangTai,
                    Moc_MFilesInfo.Moc_MFiles.FaQiBuMen,
                    Moc_MFilesInfo.Moc_MFiles.YiJiaoRen,
                    Moc_MFilesInfo.Moc_MFiles.JieShouRen,
                    Moc_MFilesInfo.Moc_MFiles.JieShouRiQi,
                    Moc_MFilesInfo.Moc_MFiles.BeiZhu)
                    .Where((Moc_MFilesInfo.Moc_MFiles.Tid == Tid) && (Moc_MFilesInfo.Moc_MFiles.Eid == Eid))
                    .ToDataSet())
            {
                rptFiles.DataSource = dt2;
                rptFiles.DataBind();

                PagedDataSource pg2 = new PagedDataSource();
                ppFile.RecordCount = dt2.Tables[0].Rows.Count;

                DataView dv2 = dt2.Tables[0].DefaultView;
                dv2.Sort = SortString;
                pg2.DataSource = dv2;
                pg2.AllowPaging = true;
                pg2.PageSize = ppFile.PageSize;
                pg2.CurrentPageIndex = ppFile.CurrentPageIndex - 1;
                rptFiles.DataSource = pg2;
                rptFiles.DataBind();

                ppFile.CustomInfoHTML = string.Format("第<font color='red'>{0}</font>/{1}", ppFile.CurrentPageIndex.ToString(), ppFile.PageCount.ToString() + "页  每页" + ppFile.PageSize.ToString() + "条" + " 共" + ppFile.RecordCount.ToString() + "条记录");
                ppFile.CustomInfoStyle = "padding-right:10px;text-align:center;";


            }
            using (DataSet dt3 = Databases.MocolaNet.Select(Moc_OutFilesInfo.Moc_OutFiles,
                    Moc_OutFilesInfo.Moc_OutFiles.ID,
                    Moc_OutFilesInfo.Moc_OutFiles.Name,
                    Moc_OutFilesInfo.Moc_OutFiles.WenJianHao,
                    Moc_OutFilesInfo.Moc_OutFiles.FaWenRiQi,
                    Moc_OutFilesInfo.Moc_OutFiles.FaWenJiGuan,
                    Moc_OutFilesInfo.Moc_OutFiles.JieShouRiQi,
                    Moc_OutFilesInfo.Moc_OutFiles.BaoCunQiXian,
                    Moc_OutFilesInfo.Moc_OutFiles.CunDangHao,
                    Moc_OutFilesInfo.Moc_OutFiles.ZhuangTai,
                    Moc_OutFilesInfo.Moc_OutFiles.BeiZhu)
                    .Where((Moc_OutFilesInfo.Moc_OutFiles.Tid == Tid) && (Moc_OutFilesInfo.Moc_OutFiles.Eid == Eid))
                    .ToDataSet())
            {
                rptOutFiles.DataSource = dt3;
                rptOutFiles.DataBind();

                PagedDataSource pg3 = new PagedDataSource();
                ppOutFile.RecordCount = dt3.Tables[0].Rows.Count;

                DataView dv3 = dt3.Tables[0].DefaultView;
                dv3.Sort = SortString;
                pg3.DataSource = dv3;
                pg3.AllowPaging = true;
                pg3.PageSize = ppOutFile.PageSize;
                pg3.CurrentPageIndex = ppFile.CurrentPageIndex - 1;
                rptOutFiles.DataSource = pg3;
                rptOutFiles.DataBind();

                ppOutFile.CustomInfoHTML = string.Format("第<font color='red'>{0}</font>/{1}", ppOutFile.CurrentPageIndex.ToString(), ppOutFile.PageCount.ToString() + "页  每页" + ppOutFile.PageSize.ToString() + "条" + " 共" + ppOutFile.RecordCount.ToString() + "条记录");
                ppOutFile.CustomInfoStyle = "padding-right:10px;text-align:center;";

            }
        }

        private string SortString
        {
            get
            {
                return ViewState["Sort"] == null ? "ID desc" : ViewState["Sort"].ToString();
            }

            set
            {
                string SortValue = value;
                if (SortString.ToLower().IndexOf("desc") < 0)
                {
                    ViewState["Sort"] = SortValue + " desc";
                }
                else
                {
                    ViewState["Sort"] = SortValue + " asc";
                }
            }
        }
        /* END: [#5] */

        protected void rptMaps_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Literal lblTuFu = e.Item.FindControl("lblTuFu") as Literal;
            Literal lblZaiTi = e.Item.FindControl("lblZaiTi") as Literal;
            Literal lblCaiZhi = e.Item.FindControl("lblCaiZhi") as Literal;
            Literal lblMiJi = e.Item.FindControl("lblMiJi") as Literal;
            Literal lblBaoGuanQiXian = e.Item.FindControl("lblBaoGuanQiXian") as Literal;
            Literal lblZhuangTai = e.Item.FindControl("lblZhuangTai") as Literal;

            /*Begin:[#23]*/
            HiddenField hfMapsID = e.Item.FindControl("hfMapsID") as HiddenField;
            hfMapsID.Value = DataBinder.Eval(e.Item.DataItem, "ID").ToString();
            /*End:[#23]*/

            lblTuFu.Text = "A" + lblTuFu.Text;
            lblZaiTi.Text = lblZaiTi.Text == "0" ? "纸质" : (lblZaiTi.Text == "1" ? "电子档" : lblZaiTi.Text == "2" ? "光盘" : "-");
            lblCaiZhi.Text = lblCaiZhi.Text == "0" ? "无" : (lblCaiZhi.Text == "1" ? "蓝图" : (lblCaiZhi.Text == "2" ? "白图" : "-"));
            lblMiJi.Text = lblMiJi.Text == "0" ? "公开" : (lblMiJi.Text == "1" ? "限制" : (lblMiJi.Text == "2" ? "秘密" : "-"));
            lblBaoGuanQiXian.Text = lblBaoGuanQiXian.Text == "0" ? "永久" : (lblBaoGuanQiXian.Text == "1" ? "长期" : (lblBaoGuanQiXian.Text == "2" ? "短期" : "-"));
            lblZhuangTai.Text = lblZhuangTai.Text == "0" ? "无效" : "有效";

        }

        protected void rptFiles_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Literal lblZaiTi = e.Item.FindControl("lblZaiTi") as Literal;
            Literal lblCaiZhi = e.Item.FindControl("lblCaiZhi") as Literal;
            Literal lblMiJi = e.Item.FindControl("lblMiJi") as Literal;
            Literal lblBaoGuanQiXian = e.Item.FindControl("lblBaoGuanQiXian") as Literal;
            Literal lblZhuangTai = e.Item.FindControl("lblZhuangTai") as Literal;

            /*Begin:[#23]*/
            HiddenField hfMapsID = e.Item.FindControl("hfFileID") as HiddenField;
            hfMapsID.Value = DataBinder.Eval(e.Item.DataItem, "ID").ToString();
            /*End:[#23]*/

            lblZaiTi.Text = lblZaiTi.Text == "0" ? "纸质" : (lblZaiTi.Text == "1" ? "电子档" : lblZaiTi.Text == "2" ? "光盘" : "-");
            lblCaiZhi.Text = lblCaiZhi.Text == "0" ? "文档" : (lblCaiZhi.Text == "1" ? "照片" : (lblCaiZhi.Text == "2" ? "照证" : (lblCaiZhi.Text == "3" ? "图片" : "-")));
            lblMiJi.Text = lblMiJi.Text == "0" ? "公开" : (lblMiJi.Text == "1" ? "限制" : (lblMiJi.Text == "2" ? "秘密" : "-"));
            lblBaoGuanQiXian.Text = lblBaoGuanQiXian.Text == "0" ? "永久" : (lblBaoGuanQiXian.Text == "1" ? "长期" : (lblBaoGuanQiXian.Text == "2" ? "短期" : "-"));
            lblZhuangTai.Text = lblZhuangTai.Text == "0" ? "原件" : (lblZhuangTai.Text == "1" ? "复印件" : (lblZhuangTai.Text == "2" ? "电子档" : "-"));
        }

        protected void ppMaps_PageChanged(object sender, EventArgs e)
        {
            BindData();
        }

        protected void ppFile_PageChanged(object sender, EventArgs e)
        {
            BindData();
        }

        protected void rptOutFiles_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Literal lblBaoGuanQiXian = e.Item.FindControl("lblBaoGuanQiXian") as Literal;
            Literal lblZhuangTai = e.Item.FindControl("lblZhuangTai") as Literal;
            HiddenField hfMapsID = e.Item.FindControl("hfOutFileID") as HiddenField;
            hfMapsID.Value = DataBinder.Eval(e.Item.DataItem, "ID").ToString();
            lblBaoGuanQiXian.Text = lblBaoGuanQiXian.Text == "0" ? "永久" : (lblBaoGuanQiXian.Text == "1" ? "长期" : (lblBaoGuanQiXian.Text == "2" ? "短期" : "-"));
            lblZhuangTai.Text = lblZhuangTai.Text == "0" ? "原件" : (lblZhuangTai.Text == "1" ? "复印件" : (lblZhuangTai.Text == "2" ? "电子档" : "-"));
        }

        protected void ppOutFile_PageChanged(object sender, EventArgs e)
        {
            BindData();
        }

        /*Begin:[#23]*/

        #region  移动目录功能
        /// <summary>
        /// 移动文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnMove_Click(object sender, EventArgs e)
        {
            string IsPassword = ConfigurationManager.AppSettings["PasswordConfirm"];
            if (IsPassword == "1")
            {
                if (IsMatchPassword(txtPassword.Text.Trim()))
                    Move();
                else
                    Alert.Show("您没有移动文件的权限，请提供正确的密码！");
            }
            else
                Move();
        }
        /// <summary>
        /// 是否是目录级别
        /// </summary>
        /// <returns></returns>
        private bool IsValidate(int tid)
        {
            return tid > 2;
        }
        /// <summary>
        /// 移动文件或图纸至目录
        /// 可同时移动
        /// </summary>
        private void Move()
        {
            if (tvFolder.SelectedNode != null)
            {
                string[] arr = tvFolder.SelectedNode.Value.Split('|');
                if (arr.Length >= 3)
                {
                    string uid = arr[0]; //对应图纸或文件的tid
                    string eid = arr[1]; //对应图纸或文件的eid
                    string tid = arr[2]; //type:目录所属的级别
                    if (IsValidate(Int32.Parse(tid))) //目录级才能移动
                    {
                        bool b = Move_Maps(eid, uid);
                        b = Move_Files(eid, uid);
                        b = Move_OutFiles(eid, uid);
                        if (b)
                            Alert.Show("操作成功！");
                        else
                            Alert.Show("操作失败！");
                    }
                    else  //给出提示消息：不能移动类目或阶段
                    {
                        Alert.Show("不能移动到项目或阶段下！");
                    }
                }
            }
            else
            {
                Alert.Show("请选择目录！");
            }
        }
        /// <summary>
        /// 移动图纸
        /// </summary>
        private bool Move_Maps(string eid, string tid)
        {
            bool IsResult = true;
            List<string> listID = new List<string>();
            foreach (RepeaterItem item in rptMaps.Items)
            {
                CheckBox chk = item.FindControl("chkMapItem") as CheckBox;
                HiddenField hfFileID = item.FindControl("hfMapsID") as HiddenField;
                if (chk != null && hfFileID != null)
                {
                    if (chk.Checked)
                    {
                        listID.Add(hfFileID.Value);
                    }
                }
            }
            if (listID.Count > 0)
            {
                string sql = "update moc_mmaps set eid='{0}',tid='{1}' where id in ({2})";
                sql = string.Format(sql, eid, tid, string.Join(",", listID.ToArray()));
                DbTransaction transaction = Databases.MocolaNet.BeginTransaction(IsolationLevel.ReadCommitted);
                try
                {
                    Databases.MocolaNet.ExecuteNonQuery(transaction, CommandType.Text, sql);
                }
                catch
                {
                    IsResult = false;
                }
                finally
                {
                    if (IsResult)
                        transaction.Commit();
                    else
                        transaction.Rollback();
                }
            }
            return IsResult;
        }

        /// <summary>
        /// 移动文件
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="tid"></param>
        /// <returns></returns>
        private bool Move_Files(string eid, string tid)
        {
            bool IsResult = true;
            List<string> listID = new List<string>();
            foreach (RepeaterItem item in rptFiles.Items)
            {
                CheckBox chk = item.FindControl("chkFileItem") as CheckBox;
                HiddenField hfFileID = item.FindControl("hfFileID") as HiddenField;
                if (chk != null && hfFileID != null)
                {
                    if (chk.Checked)
                    {
                        listID.Add(hfFileID.Value);
                    }
                }
            }
            if (listID.Count > 0)
            {
                string sql = "update moc_mfiles set eid='{0}',tid='{1}' where id in ({2})";
                sql = string.Format(sql, eid, tid, string.Join(",", listID.ToArray()));
                DbTransaction transaction = Databases.MocolaNet.BeginTransaction(IsolationLevel.ReadCommitted);
                try
                {
                    Databases.MocolaNet.ExecuteNonQuery(transaction, CommandType.Text, sql);
                }
                catch
                {
                    IsResult = false;
                }
                finally
                {
                    if (IsResult)
                        transaction.Commit();
                    else
                        transaction.Rollback();
                }
            }
            return IsResult;
        }

        /// <summary>
        /// 移动外来文件
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="tid"></param>
        /// <returns></returns>
        private bool Move_OutFiles(string eid, string tid)
        {
            bool IsResult = true;
            List<string> listID = new List<string>();
            foreach (RepeaterItem item in rptOutFiles.Items)
            {
                CheckBox chk = item.FindControl("chkOutFileItem") as CheckBox;
                HiddenField hfFileID = item.FindControl("hfOutFileID") as HiddenField;
                if (chk != null && hfFileID != null)
                {
                    if (chk.Checked)
                    {
                        listID.Add(hfFileID.Value);
                    }
                }
            }
            if (listID.Count > 0)
            {
                string sql = "update Moc_OutFiles set eid='{0}',tid='{1}' where id in ({2})";
                sql = string.Format(sql, eid, tid, string.Join(",", listID.ToArray()));
                DbTransaction transaction = Databases.MocolaNet.BeginTransaction(IsolationLevel.ReadCommitted);
                try
                {
                    Databases.MocolaNet.ExecuteNonQuery(transaction, CommandType.Text, sql);
                }
                catch
                {
                    IsResult = false;
                }
                finally
                {
                    if (IsResult)
                        transaction.Commit();
                    else
                        transaction.Rollback();
                }
            }
            return IsResult;
        }

        private bool IsMatchPassword(string pwd)
        {
            string sql = "select UserPwd FROM Moc_Users where UserName='{0}'";
            sql = string.Format(sql, Page.User.Identity.Name);
            IDataReader reader = Databases.MocolaNet.ExecuteReader(CommandType.Text, sql);
            if (reader.Read())
            {
                MD5Verifier md5 = new MD5Verifier();
                return md5.verifyMd5Hash(pwd, reader["UserPwd"].ToString());
            }
            else
                return false;
        }


        private void InitMoc_Tree()
        {
            NavigateTree tree = new NavigateTree();
            string sql = "SELECT TOP 1 * FROM Moc_MTrees WHERE (ParentID > 0) ORDER BY ParentID";
            DataSet dt = Databases.MocolaNet.ExecuteDataSet(CommandType.Text, sql);
            string ParentID = dt.Tables[0].Rows[0]["ParentID"].ToString();
            tree.InitMoc_MTree(this.tvFolder, ParentID);
        }

        #endregion

        /*End:[#23]*/
    }
}
